package com.ruoyi.ftrl.service.impl;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.ftrl.domain.CommunityInfo;
import com.ruoyi.ftrl.domain.Dto.CommunityDto;
import com.ruoyi.ftrl.domain.Dto.HeatDto;
import com.ruoyi.ftrl.domain.EquipmentDocking;
import com.ruoyi.ftrl.domain.HeatInfo;
import com.ruoyi.ftrl.mapper.CommunityInfoMapper;
import com.ruoyi.ftrl.mapper.EquipmentDockingMapper;
import com.ruoyi.ftrl.mapper.HeatInfoMapper;
import com.ruoyi.ftrl.service.ICommunityInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 小区管理信息Service业务层处理
 * 
 * @author dihang
 * @date 2024-07-08
 */
@Service
public class CommunityInfoServiceImpl implements ICommunityInfoService {
    @Autowired
    private CommunityInfoMapper communityInfoMapper;
    @Autowired
    private EquipmentDockingMapper equipmentDockingMapper;
    @Autowired
    private HeatInfoMapper heatInfoMapper;


    /**
     * 查询小区管理信息
     *
     * @param id 小区管理信息主键
     * @return 小区管理信息
     */
    @Override
    public CommunityInfo selectCommunityInfoById(Long id) {
        CommunityInfo communityInfo = communityInfoMapper.selectCommunityInfoById(id);
        //todo
        return communityInfo;
    }

    /**
     * 查询小区管理信息列表
     *
     * @param communityInfo 小区管理信息
     * @return 小区管理信息
     */
    @Override
    public List<CommunityInfo> selectCommunityInfoList(CommunityInfo communityInfo) {
        return communityInfoMapper.selectCommunityInfoList(communityInfo);
    }

    /**
     * 新增小区管理信息
     *
     * @param communityInfo 小区管理信息
     * @return 结果
     */
    @Override
    public int insertCommunityInfo(CommunityInfo communityInfo) {
        communityInfo.setCreateTime(DateUtils.getNowDate());
        communityInfo.setCreateBy(SecurityUtils.getUsername());
        CommunityInfo communityInfo1 = communityInfoMapper.selectCommunityInfoByName(communityInfo.getName());
        if (communityInfo1 != null) {
            throw new ServiceException("该小区已存在，不能进行重复添加");
        }
        return communityInfoMapper.insertCommunityInfo(communityInfo);
    }

    /**
     * 修改小区管理信息
     *
     * @param communityInfo 小区管理信息
     * @return 结果
     */
    @Override
    public int updateCommunityInfo(CommunityInfo communityInfo) {
        communityInfo.setUpdateTime(DateUtils.getNowDate());
        communityInfo.setUpdateBy(SecurityUtils.getUsername());
        return communityInfoMapper.updateCommunityInfo(communityInfo);
    }

    /**
     * 批量删除小区管理信息
     *
     * @param ids 需要删除的小区管理信息主键
     * @return 结果
     */
    @Override
    public int deleteCommunityInfoByIds(Long[] ids) {
        return communityInfoMapper.deleteCommunityInfoByIds(ids);
    }

    /**
     * 删除小区管理信息信息
     *
     * @param id 小区管理信息主键
     * @return 结果
     */
    @Override
    public int deleteCommunityInfoById(Long id) {
        return communityInfoMapper.deleteCommunityInfoById(id);
    }

    /**
     * 根据热力站id查询子级小区列表
     */
    @Override
    public List<CommunityInfo> selectCommunityInfoLists(Long id) {
        return communityInfoMapper.selectCommunityInfoLists(id);
    }
    public static void main(String[] args) {
        String roomNumber = "2-3-601"; // 当前房间号
        String[] parts = roomNumber.split("-"); // 分割字符串
        int building = Integer.parseInt(parts[0]); // 楼栋
        int unit = Integer.parseInt(parts[1]); // 单元
        int room = Integer.parseInt(parts[2]); // 房间号
        System.out.println(room);
        if (String.valueOf(room).charAt(0) == '1'){
            System.out.println("这间房间是底层");
        }
        if (String.valueOf(room).charAt(0) == '6'){
            System.out.println("这间房间是顶层");
        }
        String upperRoom = building + "-" + unit + "-" + (room + 100); // 上层房间号
        String lowerRoom = building + "-" + unit + "-" + (room - 100); // 下层房间号

        // 在这里假设房间号的格式保持一致。
        // 获取上下层房间号（假设楼层在房间号中编码，简单实现）

        // 假设房间在每一层的房间号不变，并且上下层的单元和楼栋也保持不变。


        System.out.println("当前房间号: " + roomNumber);
        System.out.println("上层房间号: " + upperRoom);
        System.out.println("下层房间号: " + lowerRoom);

//        String currentRoom = "2-3-1201";
//        String[] rooms = getAdjacentRooms(currentRoom);
//        System.out.println("Upper floor room: " + rooms[0]);
//        System.out.println("Lower floor room: " + rooms[1]);

    }
    public static String[] getAdjacentRooms(String currentRoom) {
        String[] parts = currentRoom.split("-");

        int building = Integer.parseInt(parts[0]);
        int unit = Integer.parseInt(parts[1]);
        int room = Integer.parseInt(parts[2]);

        // Extract floor and room within the floor
        int floor = room / 100;
        int roomWithinFloor = room % 100;

        // Calculate upper and lower floor room numbers
        int upperFloorRoom = (floor + 1) * 100 + roomWithinFloor;
        int lowerFloorRoom = (floor - 1) * 100 + roomWithinFloor;

        // Format the new room numbers
        String upperRoom = building + "-" + unit + "-" + String.format("%03d", upperFloorRoom);
        String lowerRoom = building + "-" + unit + "-" + String.format("%03d", lowerFloorRoom);

        return new String[]{upperRoom, lowerRoom};
    }
    /**
     * 供热概况（大屏驾驶舱）
     */
    @Override
    public HeatDto selectCommunityInfo() {
        HeatDto heatDto = new HeatDto();
        //入网面积（㎡）
        heatDto.setArea("16799");
        //实际面积（㎡）
        heatDto.setAreas("16799");
        //开始供暖时间
        // 获取当前年份
        int currentYear = LocalDate.now().getYear();
        // 拼接日期为当前年份的11月15日
        LocalDate heatingStartDate = LocalDate.of(currentYear-1, 11, 15);
        // 格式化日期为字符串（格式为 YYYY-MM-DD）
        String heatingStartDateString = heatingStartDate.toString();
        heatDto.setStarTime(heatingStartDateString);
        //已供暖天数（天）
        LocalDate today = LocalDate.now();
        if (today.isBefore(heatingStartDate)) {
            heatDto.setDays("--");
        } else {
            long daysOfHeating = ChronoUnit.DAYS.between(heatingStartDate, today);
            heatDto.setDays(String.valueOf(daysOfHeating));
        }
        //距离供暖结束（天）
        // 供暖结束日期（下一年的3月15日）
        LocalDate heatingEndDate = LocalDate.of(currentYear + 1, 3, 15);
        // 判断当前日期是否在供暖期间
        if (today.isBefore(heatingStartDate)) {
           heatDto.setEndDays("--");
        } else if (today.isAfter(heatingEndDate)) {
            heatDto.setEndDays("--");
        }else {
            // 计算距离供暖结束的天数
            long daysUntilHeatingEnds = ChronoUnit.DAYS.between(today, heatingEndDate)-365;
            if (daysUntilHeatingEnds > 0) {
                heatDto.setEndDays(String.valueOf(daysUntilHeatingEnds));
            }else {
                heatDto.setEndDays("供暖已结束");
            }
        }
            //供暖小区总数（个）
            Long count = communityInfoMapper.selectCommunityInfoListCount();
            heatDto.setCount(count);




        return heatDto;
    }
    /**
     * 供热质量（大屏驾驶舱）
     * @return
     */
    @Override
    public List<CommunityDto> selectCommunityInfoListHot() {
        // 查询所有小区
        List<CommunityInfo> communityInfoList = this.selectCommunityInfoList(new CommunityInfo());
        // 获取每个小区的名字
        List<String> list = communityInfoList.stream().map(CommunityInfo::getName).toList();
        List<CommunityDto> communityDtoList = new ArrayList<CommunityDto>();

        for (String communityName : list) {
            CommunityDto communityDto = new CommunityDto();
            communityDto.setName(communityName);

            // 获取该小区的温度数据
            List<BigDecimal> temperatures = equipmentDockingMapper.getTemperaturesByCommunityName(communityName);

            // 计算供热质量
            if (!temperatures.isEmpty()) {
                long countAbove18 = temperatures.stream()
                        .filter(temp -> temp.compareTo(BigDecimal.valueOf(18)) >= 0)
                        .count();
                double qualityPercentage = ((double) countAbove18 / temperatures.size()) * 100;
                communityDto.setQuality(String.format("%.2f%%", qualityPercentage));
            } else {
                communityDto.setQuality("--");
            }

            communityDtoList.add(communityDto);
        }
        return communityDtoList;
    }

    /**
     * 小区管理（根据热力站id查询）GIS模块
     * @param id
     * @return
     */

    @Override
    public List<CommunityInfo> selectCommunityInfoListGIS(Long id) {
        List<CommunityInfo> communityInfoList = communityInfoMapper.selectCommunityInfoLists(id);
        //将该热力站下的每个小区的室内平均温度、回水温度、供水温度进行计算并赋值
//        for (CommunityInfo communityInfo : communityInfoList) {
//            //小区的室内平均温度
//            EquipmentDocking equipmentDocking = equipmentDockingMapper.selectByNameAvg(communityInfo.getName());
//            if (equipmentDocking != null) {
//                communityInfo.setField3(String.valueOf(equipmentDocking.getAverageTemperature()));
//            }else {
//                communityInfo.setField3("--");
//            }
//            //小区的进水温度
//            HeatInfo heatInfo = heatInfoMapper.selectHeatInfoByName1(communityInfo.getName());
//            if (heatInfo != null) {
//                if (heatInfo.getIntavg()==null){
//                    communityInfo.setField4("--");
//                }else {
//                    communityInfo.setField4(String.valueOf(heatInfo.getIntavg()));
//                }
//            }else {
//                communityInfo.setField4("--");
//            }
//
//            //小区的回水温度
//            HeatInfo heatInfo1 = heatInfoMapper.selectHeatInfoByNames2(communityInfo.getName());
//            if (heatInfo1 != null) {
//                if (heatInfo1.getIntavg()==null){
//                    communityInfo.setField5("--");
//                }else {
//                    communityInfo.setField5(String.valueOf(heatInfo.getIntavg()));
//                }
//            }else {
//                communityInfo.setField5("--");
//            }
//
//
//        }

        return communityInfoList;
    }
}

